package org.csu.tank.collision;

import com.almasb.fxgl.dsl.components.EffectComponent;
import com.almasb.fxgl.dsl.components.HealthIntComponent;
import com.almasb.fxgl.entity.Entity;
import com.almasb.fxgl.physics.CollisionHandler;
import org.csu.tank.GameType;
import org.csu.tank.client.TankClient;
import org.csu.tank.components.DataComponent;
import org.csu.tank.components.PlayerComponent;
import org.csu.tank.effects.HelmetEffect;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import static com.almasb.fxgl.dsl.FXGL.*;

public class BulletPlayerEnemyHandler extends CollisionHandler {

      TankClient tc;

      public BulletPlayerEnemyHandler(TankClient tc) {
            super(GameType.BULLET, GameType.PlAERY_ENEMY);
            this.tc = tc;
      }

      protected void onCollisionBegin(Entity bullet, Entity player) {
            AtomicBoolean isCollision = new AtomicBoolean(true);
            bullet.getComponentOptional(DataComponent.class).ifPresent(dataComponent -> {
                  if (dataComponent.getId() == player.getComponent(PlayerComponent.class).getId()) {
                        System.out.println("id 相同不碰撞");
                        isCollision.set(false);
                  }
            });
            if (isCollision.get() == false)
                  return;

            play("normalBomb.wav");
            if (player.getComponent(EffectComponent.class).hasEffect(HelmetEffect.class)) {
                  bullet.removeFromWorld();
                  return;
            }
            spawn("explode", bullet.getCenter().getX() - 25, bullet.getCenter().getY() - 20);
            bullet.removeFromWorld();
            HealthIntComponent hp = player.getComponent(HealthIntComponent.class);
            hp.damage(1);

            if (hp.isZero()) {
                  player.removeFromWorld();
                  inc("nowEnemyNum", -1);
                  tc.addKills();
                  List<PlayerComponent> playerComponentList = tc.getPlayerComponentList();
                  for (PlayerComponent playerComponent : playerComponentList) {
                        if (playerComponent.getId() == player.getComponent(PlayerComponent.class).getId()) {
                              playerComponentList.remove(playerComponent);
                              break;
                        }
                  }
            }
      }
}
